package com.zlk.algorithm.huawei.leetcode.matrix;

import org.junit.Test;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: algorithm
 * @ClassName Code12_spiralOrder
 * @description:螺旋矩阵
 *
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 *
 * @author: slfang
 * @create: 2025-01-06 10:58
 * @Version 1.0
 **/
public class Code12_spiralOrder {
    int l;
    int r;
    int t;
    int b;


    public List<Integer> spiralOrder(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        l = 0;
        r = m-1;
        t = 0;
        b = n-1;
        int indexI=0;
        int indexJ=0;
        List<Integer> ans = new ArrayList<>();
        loopRight(indexI,indexJ,matrix,ans);
        return ans;
    }

    private void loopRight(int indexI, int indexJ, int[][] matrix, List<Integer> ans) {
        while (indexJ<=r){
            ans.add(matrix[indexI][indexJ++]);
        }
        t++;
        if(indexI!=b){
            loopDown(++indexI,--indexJ,matrix,ans);
        }

    }

    private void loopDown(int indexI, int indexJ, int[][] matrix, List<Integer> ans) {
        while (indexI<=b){
            ans.add(matrix[indexI++][indexJ]);
        }
        r--;
        if(indexJ!=l){
            loopLeft(--indexI,--indexJ,matrix,ans);
        }

    }

    private void loopLeft(int indexI, int indexJ, int[][] matrix, List<Integer> ans) {
        while (indexJ>=l){
            ans.add(matrix[indexI][indexJ--]);
        }
        b--;
        if(indexI!=t){
            loopUp(--indexI,++indexJ,matrix,ans);
        }
    }

    private void loopUp(int indexI, int indexJ, int[][] matrix, List<Integer> ans) {
        while (indexI>=t){
            ans.add(matrix[indexI--][indexJ]);
        }
        l++;
        if(indexJ!=r){
            loopRight(++indexI,++indexJ,matrix,ans);
        }
    }

    @Test
    public void test(){
        int[][] matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        List<Integer> list = spiralOrder(matrix);
        System.out.println(list);
    }
}
